function dumpDebug(text) {
    dump("[FIB] "+text+"\n");
}

var badgets = [];
var prefs = null;

function initOptions() {
  
    tabScripts = document.getElementById("tabScripts");
    scriptName = document.getElementById("scriptName");
    scriptDesc = document.getElementById("scriptDesc");
    includedPages = document.getElementById("includedPages");

    btnEdit = document.getElementById("btnEdit");
    btnInstall = document.getElementById("btnInstall");
    btnUninstall = document.getElementById("btnUninstall");
    
    btnEdit.addEventListener("command", editCommand, false);
    btnInstall.addEventListener("command", installCommand, false);
    btnUninstall.addEventListener("command", uninstallCommand, false);
        
    tabScripts.addEventListener("select", updateDetails, false);
    
      
    badgets = getScriptList();
    populatetabScripts();
};

function editCommand() {
    var fileServ = Components.classes["@mozilla.org/file/directory_service;1"]
                         .getService(Components.interfaces.nsIProperties); 
    var file = fileServ.get("ProfD", Components.interfaces.nsIFile);
    
    file.append("badgets");
    file.append(tabScripts.getSelectedItem(0).script.file);
    
    this.prefs = Components.classes["@mozilla.org/preferences-service;1"].
                getService(Components.interfaces.nsIPrefService);
    var branch = this.prefs.getBranch("extensions.faviconbadge.");
    var editor = branch.getCharPref("editor");
    
    if (editor!="") {
        try {
            var editorApp = Components.classes["@mozilla.org/file/local;1"]
                                 .createInstance(Components.interfaces.nsILocalFile);
            var osString = Components.classes["@mozilla.org/xre/app-info;1"]
                .getService(Components.interfaces.nsIXULRuntime).OS;
            
            if (osString == "Darwin") {
                editorApp.initWithPath("/usr/bin/open");
            }else{
                editorApp.initWithPath(editor);            
            }
            
            var process = Components.classes["@mozilla.org/process/util;1"]
                                    .createInstance(Components.interfaces.nsIProcess);
            process.init(editorApp);
            
            dumpDebug(file.path);
            if (osString == "Darwin") {
                var args = ["-a" + editor, file.path]
            }else{
                var args = [file.path];
            }
            process.run(false, args, args.length);
        }catch(e){
            alert(e);
        }
    }else{
        var nsIFilePicker = Components.interfaces.nsIFilePicker;
        var filePicker = Components.classes["@mozilla.org/filepicker;1"]
                                 .createInstance(nsIFilePicker);
        
        filePicker.appendFilters(nsIFilePicker.filterApps);
        filePicker.init(window, stringBundle("editor.filepicker.title"),
                      nsIFilePicker.modeOpen);
        
        if (filePicker.show() != nsIFilePicker.returnOK) {
            return null;
        }
        
        if (filePicker.file.exists() && filePicker.file.isExecutable()) {    
            branch.setCharPref("editor", filePicker.file.path);
            this.prefs.savePrefFile(null);
        } else {
            alert(stringBundle("error.editor.pick"));
        }    
    }
    
};

function installCommand() {
    var nsIFilePicker = Components.interfaces.nsIFilePicker;
    var filePicker = Components.classes["@mozilla.org/filepicker;1"]
            .createInstance(nsIFilePicker);

    filePicker.appendFilter("Javascript", "*.js");
    filePicker.init(window, stringBundle("badget.filepicker.title"), nsIFilePicker.modeOpen);

    if (filePicker.show() != nsIFilePicker.returnOK) {
        return null;
    }
        
    if (filePicker.file.exists() && filePicker.file.leafName.indexOf(".js") > -1) {
        copyScriptToProfile(filePicker.file);
        badgets = getScriptList(true);
        initOptions();
    } else {
        alert(stringBundle("error.badget.pick"));
    }
};

function uninstallCommand() {
    var fileServ = Components.classes["@mozilla.org/file/directory_service;1"]
                         .getService(Components.interfaces.nsIProperties); 
    var file = fileServ.get("ProfD", Components.interfaces.nsIFile);
    
    file.append("badgets");
    file.append(tabScripts.getSelectedItem(0).script.file);
    
    if (file.exists()) {
        removeScriptFromProfile(file);
        badgets = getScriptList(true);
        initOptions();
    }else{
        alert(bundleString("file.dont.exists"));
    }
};

function populatetabScripts() {
   while (tabScripts.hasChildNodes()) {
    tabScripts.removeChild(tabScripts.childNodes[0]);
  }
  
    for (var i = 0, script = null; (script = badgets[i]); i++) {
    dumpDebug(i);
        addListitem(script, i);
  }
};

function addListitem(script, i) {
    var listitem = document.createElement("listitem");
    
    listitem.setAttribute("label", script.name);
    listitem.setAttribute("crop", "end");
    listitem.script = script;
    listitem.index = i;
    
    if (!script.enabled) {
        listitem.style.color = "gray";
    }
    
    tabScripts.appendChild(listitem);
};

function updateDetails() {
  if (tabScripts.selectedCount == 0) {
    selectedScript = null;
    header.value = " ";
    description.value = " ";
    chkEnabled.checked = true;
    pagesControl.clear();
  } else {
        var script = tabScripts.getSelectedItem(0).script;
        scriptName.value = script.name;
        scriptDesc.value = script.description;
        
        populateIncludedPages(script);
    }
};

function populateIncludedPages(script) {

  while (includedPages.hasChildNodes()) {
    includedPages.removeChild(includedPages.childNodes[0]);
  }
              
    for (var i = 0, page = null; (page = script["includes"][i]); i++) {
    dumpDebug(page);
        addIncludedPage(page, i);
  }
};

function addIncludedPage(page, i) {
    var listitem = document.createElement("listitem");
    
    listitem.setAttribute("label", page);
    listitem.setAttribute("crop", "end");
    listitem.index = i;
    
    includedPages.appendChild(listitem);
};

window.addEventListener("load", function(ev) { initOptions(); }, false);
